package org.freespace.api;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class JMeterCmdHandler extends SimpleChannelInboundHandler<ByteBuf> {

    public String returnMsg = null;

    private String cmd = null;

    public static String JMETER_START = "start:-n -t ";
    public static String JMETER_STOP = "stop:";

    public JMeterCmdHandler(String cmd) {
        this.cmd = cmd;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        this.returnMsg = byteBuf.toString(CharsetUtil.UTF_8);
        log.info("client received: {}", returnMsg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        byte[] bytes = cmd.getBytes(StandardCharsets.UTF_8);
        ProtocolBean protocolBean = new ProtocolBean((byte) 0xA, (byte) 0xC, bytes.length, cmd);
        ctx.writeAndFlush(protocolBean);
    }
}
